package com.woniuxy.service;


import com.baomidou.dynamic.datasource.annotation.DS;
import com.woniuxy.entity.User;
import com.woniuxy.entity.UserInfo;
import com.woniuxy.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@Component
public class SecurityService implements UserDetailsService,SaasService {
    @Autowired
    PasswordEncoder passwordEncoder;

    @Resource
    UserMapper userMapper;

    @Autowired
    HttpServletRequest httpServletRequest;
    /**
     *
     * @param
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {

        //根据用户名到数据库中查询用户信息，主要包括账号密码 权限
        User user = userMapper.queryUserByAccount(account);
        if(user != null){
            user.getPassword();//如果密码已经加密，直接放入
            String pw = passwordEncoder.encode(user.getPassword());
            List<String> authCode = user.getAuthCode();
            String authCodeStr = String.join(",", authCode);


//            return new User(employee.getAccount(),pw,
//                    AuthorityUtils.commaSeparatedStringToAuthorityList(authCodeStr));
            return new UserInfo(user.getAccount(),pw,
                    AuthorityUtils.commaSeparatedStringToAuthorityList(authCodeStr),user.getId());
        }else {
            throw new UsernameNotFoundException("用户名不存在");
        }

    }
}
